<template>
  <!-- 弹窗对话框，根据mode的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @close="handleClose"
    size="90%"
  >
    <t-loading text="加载中..." size="small" v-if="pageData.loading" />
    <div v-if="!pageData.loading">
      <FormInfo v-if="mode !== 'new'">
        <template #left>订单号：{{ pageData.formData.orderId }}</template>
        <template #content>
          <t-form>
            <t-row>
              <t-col :span="3">
                <t-form-item label="创建人">
                  <div class="form__text">{{ pageData.formData.createdByName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="创建日期">
                  <div class="form__text">{{ dayjs(pageData.formData.createdTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="更新人">
                  <div class="form__text">{{ pageData.formData.updatedByName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="更新日期">
                  <div class="form__text">{{ dayjs(pageData.formData.updatedTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
                </t-form-item>
              </t-col>
            </t-row>
          </t-form>
        </template>
      </FormInfo>
      <!-- 基本信息 -->
      <t-form ref="formInstance" :rules="pageData.formRules" :disabled="pageData.readOnly" :data="pageData.formData">
        <FormInfo>
          <template #left>出运基本信息</template>
          <template #content>
            <t-space direction="vertical" style="width: 100%" size="large">
              <t-row>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="发票号" name="ticketId">
                    <t-input
                      :showLimitNumber="true"
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.ticketId"
                      maxlength="50"
                    />
                    <div v-else class="form__text">{{ pageData.formData.ticketId }}</div>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="发票日期" name="ticketDate">
                    <t-date-picker
                      clearable
                      :showLimitNumber="true"
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.ticketDate"
                      style="width: 100%"
                    />
                    <div v-else class="form__text">
                      {{ dayjs(pageData.formData.ticketDate).format("YYYY-MM-DD HH:mm:ss") }}
                    </div>
                  </t-form-item>
                </t-col>
              </t-row>
              <t-row>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="海关编码" name="customsId">
                    <t-input
                      :showLimitNumber="true"
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.customsId"
                      maxlength="50"
                    />
                    <div v-else class="form__text">{{ pageData.formData.customsId }}</div>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="监管方" name="regulators">
                    <t-select
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.regulators"
                      :options="pageData.regulatorsDict"
                    />
                    <div v-else class="form__text">
                      {{ getValueBySelectData(pageData.regulatorsDict, pageData.formData.regulators) }}
                    </div>
                  </t-form-item>
                </t-col>
              </t-row>
              <t-row>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="运输方式" name="expressMethod">
                    <t-select
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.expressMethod"
                      :options="pageData.expressMethodDict"
                    />
                    <div v-else class="form__text">
                      {{ getValueBySelectData(pageData.expressMethodDict, pageData.formData.expressMethod) }}
                    </div>
                  </t-form-item>
                </t-col>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="免征性质" name="freeTaxNature">
                    <t-select
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.freeTaxNature"
                      :options="pageData.freeTaxNatureDict"
                    />
                    <div v-else class="form__text">
                      {{ getValueBySelectData(pageData.freeTaxNatureDict, pageData.formData.freeTaxNature) }}
                    </div>
                  </t-form-item>
                </t-col>
              </t-row>
              <t-row>
                <t-col :span="6">
                  <t-form-item :labelWidth="120" label="包装种类" name="packetType">
                    <t-input
                      :showLimitNumber="true"
                      v-if="!pageData.readOnly"
                      v-model="pageData.formData.packetType"
                      maxlength="50"
                    />
                    <div v-else class="form__text">{{ pageData.formData.packetType }}</div>
                  </t-form-item>
                </t-col>
              </t-row>
            </t-space>
          </template>
        </FormInfo>

        <FormInfo>
          <template #left>出运商品信息</template>
          <template #content>
            <FormTable
              rowKey="localUUID"
              :buttons="pageData.goodsButtons"
              :tableData="pageData.formData.products"
              :columns="pageData.goodsColumns"
              :footData="[{}]"
              @currentChange="handleGoodsTableSelectChange"
            >
              <!-- <template #operation="{ row }">
              <div v-if="row.hasDeleted === 0" class="form-table__row_operations">
                <t-link variant="text" theme="danger" @click="handleDeleteGood(row)" :disabled="pageData.readOnly"
                  >删除</t-link
                >
              </div>
              <div v-else>
                <t-link theme="danger" variant="text" @click="handleUnDeleteGood(row)">撤销删除</t-link>
              </div>
            </template> -->
            </FormTable>
          </template>
        </FormInfo>
      </t-form>
    </div>
  </t-drawer>

  <SelectTable
    v-if="pageData.sourceRegion.show"
    :loading="pageData.sourceRegion.loading"
    title="选择国家/地区"
    :showDialog="pageData.sourceRegion.show"
    width="60vw"
    zIndex="3500"
    rowSelectionType="single"
    :tableData="pageData.sourceRegion.data.records"
    :columns="pageData.sourceRegion.columns"
    @onConfirm="handleSourceRegionConfirm"
    @onCancel="handleSourceRegionClose"
    :pagination="pageData.sourceRegion.pagination"
    @page-change="handleSourceRegionPageChange"
    :filter-value="pageData.sourceRegion.filterValue"
    @filter-change="handleSourceRegionFilterChange"
  />

  <SelectTable
    v-if="pageData.expressRegion.show"
    :loading="pageData.expressRegion.loading"
    title="选择国家/地区"
    :showDialog="pageData.expressRegion.show"
    width="60vw"
    zIndex="3500"
    rowSelectionType="single"
    :tableData="pageData.expressRegion.data.records"
    :columns="pageData.sourceRegion.columns"
    @onConfirm="handleExpressRegionConfirm"
    @onCancel="handleExpressRegionClose"
    :pagination="pageData.expressRegion.pagination"
    @page-change="handleExpressRegionPageChange"
    :filter-value="pageData.expressRegion.filterValue"
    @filter-change="handleExpressRegionFilterChange"
  />

  <SelectExpressDetail
    v-if="pageData.showSelectExpressDetail"
    :showDialog="pageData.showSelectExpressDetail"
    @onClose="handleSelectExpressDetailClose"
    @onConfirm="handleSelectExpressDetailConfirm"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { defineAsyncComponent, reactive, ref, toRaw, watch } from "vue";
import { type FormInstanceFunctions, type TableProps } from "tdesign-vue-next";

// TS 类型文件
import type { ISelectDataType } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";
import { v4 as uuidv4 } from "uuid";
import dayjs from "dayjs";
import { generateFormattedNumber, getValueBySelectData, newPrecision } from "@/utils/tools";

// 常量
import { EDIT_FORM_SAVE_BUTTON } from "@/common/constants";
import { PAGINATION_VALUE } from "@/common/constants";

// API
import { getDictValue } from "@/api/dict";
import { getRegionList } from "@/api/region";

// 动态组件
const SelectExpressDetail = defineAsyncComponent(() => import("./SelectExpressDetail.vue"));

const props = defineProps(["id", "dialogVisible", "mode", "statusDict"]);
const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/express/findOne"; // 查询接口
const CREATE_FORM_PATH = "/express/create"; // 创建接口
const UPDATE_FORM_PATH = "/express/update"; // 更新接口

// const userStore = useUserStore();

const pageData = reactive({
  loading: true,
  readOnly: false,
  formData: {
    id: "",
    status: 0,
    hasDeleted: 0,
    remark: "",
    expressId: "",
    ticketId: "",
    productsTotalNum: 0,
    kgsTotalNum: 0,
    gwsTotalNum: 0,
    bulkTotalNum: 0,
    ticketDate: "",
    expressMethod: 0,
    packetType: "",
    regulators: 0,
    freeTaxNature: 0,
    orderUUID: "",
    customerId: "",
    products: []
  } as Record<string, any>,
  formRules: {
    ticketId: [{ required: true, message: "请输入发票号码", type: "error", trigger: "blur" }],
    ticketDate: [{ required: true, message: "请输入发票日期", type: "error", trigger: "blur" }],
    customsId: [{ required: true, message: "请输入海关编码", type: "error", trigger: "blur" }],
    regulators: [{ required: true, message: "请选择监管方", type: "error", trigger: "blur" }],
    expressMethod: [{ required: true, message: "请选择运输方式", type: "error", trigger: "blur" }],
    freeTaxNature: [{ required: true, message: "请选择免征性质", type: "error", trigger: "blur" }],
    packetType: [{ required: true, message: "请选择免征性质", type: "error", trigger: "blur" }]
  },
  goodsButtons: [
    {
      name: "提取订单商品明细",
      icon: "edit",
      disabled: props.mode === "view",
      click: () => {
        handleNewGood();
      }
    }
  ],
  goodsColumns: [
    {
      colKey: "productEngName",
      title: "商品名称",
      width: 250,
      foot: () => <b>合计</b>
    },
    {
      colKey: "specification",
      title: "规格型号",
      width: 250
    },
    {
      colKey: "expressNumber",
      title: "出运数量",
      width: 250,
      foot: () => {
        return <div>{pageData.formData.productsTotalNum}</div>;
      }
    },
    {
      colKey: "unit",
      title: "单位",
      width: 250
    },
    {
      colKey: "customsId",
      title: "海关编码（HS）",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input v-model={row.customsId}></t-input>;
        } else {
          return row.customsId;
        }
      }
    },
    {
      colKey: "kgs",
      title: "净重（千克）",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          if (!row.kgs) {
            row.kgs = 0;
          }
          return <t-input-number style="width: 100%" theme="column" v-model={row.kgs}></t-input-number>;
        } else {
          return newPrecision(row.kgs, 3);
        }
      },
      foot: () => {
        return <div>{pageData.formData.kgsTotalNum}</div>;
      }
    },
    {
      colKey: "gws",
      title: "毛重（千克）",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          if (!row.gws) {
            row.gws = 0;
          }
          return <t-input-number style="width: 100%" theme="column" v-model={row.gws} />;
        } else {
          return newPrecision(row.gws, 3);
        }
      },
      foot: () => {
        return <div>{pageData.formData.gwsTotalNum}</div>;
      }
    },
    {
      colKey: "bulk",
      title: "体积（平方米）",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          if (!row.bluk) {
            row.bluk = 0;
          }
          return <t-input-number theme="column" v-model={row.bulk} />;
        } else {
          return row.bulk;
        }
      },
      foot: () => {
        return <div>{pageData.formData.bulkTotalNum}</div>;
      }
    },
    {
      colKey: "originCountry",
      title: "原产国（地区）",
      width: 250,
      cell: (h, props) => {
        if (!pageData.readOnly && props.row.hasDeleted !== 1) {
          return (
            <input-select
              value={props.row.originCountryName}
              onOnClick={() => handleSourceRegionOpen(props.rowIndex)}
            />
          );
        } else {
          return props.row.originCountryName;
        }
      }
    },
    {
      colKey: "expressCountry",
      title: "最终目的国家（地区）",
      width: 250,
      cell: (h, props) => {
        if (!pageData.readOnly && props.row.hasDeleted !== 1) {
          return (
            <input-select
              value={props.row.expressCountryName}
              onOnClick={() => handleExpressRegionOpen(props.rowIndex)}
            />
          );
        } else {
          return props.row.expressCountryName;
        }
      }
    },
    {
      colKey: "chinaSupplied",
      title: "境内货源地（省份）",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={30} v-model={row.chinaSupplied}></t-input>;
        } else {
          return row.chinaSupplied;
        }
      }
    },
    {
      colKey: "freeTax",
      title: "免征",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={30} v-model={row.freeTax}></t-input>;
        } else {
          return row.freeTax;
        }
      }
    },
    {
      colKey: "decElement",
      title: "申报要素",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={30} v-model={row.decElement}></t-input>;
        } else {
          return row.decElement;
        }
      }
    }
  ] as TableProps["columns"],
  emptyGoodFormData: {
    productId: "",
    hasDeleted: 0,
    customsId: "",
    kgs: 0,
    gws: 0,
    originCountry: "",
    bulk: 0,
    expressCountry: "",
    sourceCountry: "",
    freeTax: "",
    decElement: "",
    expressNumber: 0,
    localUUID: ""
  },
  goodsSelectedRowData: [],
  regulatorsDict: [] as ISelectDataType[],
  expressMethodDict: [] as ISelectDataType[],
  freeTaxNatureDict: [] as ISelectDataType[],
  showSelectExpressDetail: false,
  sourceRegion: {
    show: false,
    loading: false,
    rowIndex: 0,
    data: {} as Record<string, any>,
    filterValue: {
      countryName: ""
    } as Record<string, any>,
    columns: [
      {
        colKey: "countryCode",
        title: "区号",
        width: 220
      },
      {
        colKey: "countryName",
        title: "国家/地区",
        width: 230,
        filter: {
          type: "input",
          resetValue: "",
          // 按下 Enter 键时也触发确认搜索
          confirmEvents: ["onEnter"],
          showConfirmAndReset: true
        }
      }
    ],
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  },
  expressRegion: {
    show: false,
    loading: false,
    rowIndex: 0,
    data: {} as Record<string, any>,
    filterValue: {
      countryName: ""
    } as Record<string, any>,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  }
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode !== "new") {
    // } else if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = { ...resultData.data };

    if (pageData.formData.products.length > 0 && !pageData.formData.products.some((item: null) => item === null)) {
      pageData.formData.products.forEach((item: any) => {
        item.localUUID = uuidv4();
      });

      // const kgsTotalNum = pageData.formData.products.reduce((acc: number, cur: Record<string, any>) => {
      //   return acc + cur.kgs;
      // }, 0);

      // const gwsTotalNum = pageData.formData.products.reduce((acc: number, cur: Record<string, any>) => {
      //   return acc + cur.gws;
      // }, 0);

      // const bulkTotalNum = pageData.formData.products.reduce((acc: number, cur: Record<string, any>) => {
      //   return acc + cur.bulk;
      // }, 0);

      // pageData.formData.kgsTotalNum = kgsTotalNum;
      // pageData.formData.gwsTotalNum = gwsTotalNum;
      // pageData.formData.bulkTotalNum = bulkTotalNum;
    }

    // 处理后端数据使之符合表单数据格式

    pageData.loading = false;

    if (props.mode === "view") {
      pageData.readOnly = true;
    }
  } else {
    pageData.formData.expressId = `CY${generateFormattedNumber()}`;
    pageData.loading = false;
  }
};

const getRegulatorsDict = async () => {
  const resultData = await getDictValue("EXPRESS_REGULATORS");
  if (resultData.code === 200) {
    const regulatorsDict = resultData.data.map((item: Record<string, any>) => {
      return {
        label: item.dictName,
        value: item.dictValue
      };
    });
    pageData.regulatorsDict = regulatorsDict;
  }
};

const getExpressMethodDict = async () => {
  const resultData = await getDictValue("EXPRESS_METHOD");
  if (resultData.code === 200) {
    const expressMethodDict = resultData.data.map((item: Record<string, any>) => {
      return {
        label: item.dictName,
        value: item.dictValue
      };
    });
    pageData.expressMethodDict = expressMethodDict;
  }
};

const getFreeTaxNatureDict = async () => {
  const resultData = await getDictValue("EXPRESS_FREE_TAX_NATURE");
  if (resultData.code === 200) {
    const freeTaxNatureDict = resultData.data.map((item: Record<string, any>) => {
      return {
        label: item.dictName,
        value: item.dictValue
      };
    });
    pageData.freeTaxNatureDict = freeTaxNatureDict;
  }
};

// const formatWeightNum = (num: number) => {
//   return newPrecision(num, 3);
// };

// 找出数组下标
// const findGoodsArrIndex = (row: Record<string, any>) => {
//   return pageData.formData.products.findIndex((item: Record<string, any>) => item.localUUID === row.localUUID);
// };

const handleGoodsTableSelectChange = ({ keys }: { keys: Array<Number | String> }) => {
  const filteredObjects = pageData.formData.products.filter((item: Record<string, any>) =>
    keys.includes(item.localUUID)
  );
  pageData.goodsSelectedRowData = filteredObjects;
};

const handleNewGood = () => {
  // const emptyGoodFormDataToRaw = toRaw(pageData.emptyGoodFormData);
  // const emptyGoodFormData = structuredClone(emptyGoodFormDataToRaw);
  // emptyGoodFormData.localUUID = uuidv4();
  // pageData.formData.products.push(emptyGoodFormData);
  pageData.showSelectExpressDetail = true;
};

// const handleDeleteGood = (row: Record<string, any>) => {
//   const index = findGoodsArrIndex(row);
//   if (index > -1) {
//     pageData.formData.products[index].hasDeleted = 1;
//   }
// };

// const handleUnDeleteGood = (row: Record<string, any>) => {
//   const index = findGoodsArrIndex(row);
//   if (index > -1) {
//     pageData.formData.products[index].hasDeleted = 0;
//   }
// };

const handleSelectExpressDetailConfirm = (e: Record<string, any>) => {
  pageData.formData.products = e;
  pageData.formData.orderUUID = e[0].orderId;
  pageData.formData.customerId = e[0].customerId;

  // 从商品子表里面计算商品数
  const productsTotalNum = e.reduce((acc: number, cur: Record<string, any>) => {
    return acc + cur.expressNumber;
  }, 0);

  const kgsTotalNum = e.reduce((acc: number, cur: Record<string, any>) => {
    return acc + cur.kgs;
  }, 0);

  const gwsTotalNum = e.reduce((acc: number, cur: Record<string, any>) => {
    return acc + cur.gws;
  }, 0);

  const bulkTotalNum = e.reduce((acc: number, cur: Record<string, any>) => {
    return acc + cur.bulk;
  }, 0);

  pageData.formData.productsTotalNum = productsTotalNum;
  pageData.formData.kgsTotalNum = kgsTotalNum;
  pageData.formData.gwsTotalNum = gwsTotalNum;
  pageData.formData.bulkTotalNum = bulkTotalNum;

  pageData.showSelectExpressDetail = false;
};

const handleSelectExpressDetailClose = () => {
  pageData.showSelectExpressDetail = false;
};

const handleSourceRegionOpen = (rowIndex: number) => {
  pageData.sourceRegion.rowIndex = rowIndex;
  getSourceRegionData();
  pageData.sourceRegion.show = true;
};

const getSourceRegionData = async () => {
  pageData.sourceRegion.loading = true;
  const resultData = await getRegionList(
    pageData.sourceRegion.pagination.current,
    pageData.sourceRegion.pagination.pageSize,
    pageData.sourceRegion.filterValue
  );

  if (resultData.code === 200) {
    pageData.sourceRegion.data = resultData.data;
    pageData.sourceRegion.loading = false;
    pageData.sourceRegion.pagination.total = resultData.data.total;
    pageData.sourceRegion.pagination.current = resultData.data.current;
    pageData.sourceRegion.pagination.pageSize = resultData.data.size;
  }
};

const handleSourceRegionConfirm = (e: Record<string, any>) => {
  // console.log(pageData.formData.products[pageData.sourceRegion.rowIndex]);
  pageData.formData.products[pageData.sourceRegion.rowIndex].originCountry = e.options.currentRowData.id;
  pageData.formData.products[pageData.sourceRegion.rowIndex].originCountryName = e.options.currentRowData.countryName;
  pageData.sourceRegion.show = false;
};

const handleSourceRegionClose = () => {
  pageData.sourceRegion.show = false;
};

const handleSourceRegionFilterChange = (filters: Record<string, any>) => {
  pageData.sourceRegion.filterValue = filters;
  pageData.sourceRegion.pagination = structuredClone(PAGINATION_VALUE);
  getSourceRegionData();
};

const handleSourceRegionPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.sourceRegion.pagination.pageSize = pageInfo.pageSize;
  pageData.sourceRegion.pagination.current = pageInfo.current;
  getSourceRegionData();
};

const handleExpressRegionOpen = (rowIndex: number) => {
  getExpressRegionData();
  pageData.expressRegion.rowIndex = rowIndex;
  pageData.expressRegion.show = true;
};

const getExpressRegionData = async () => {
  pageData.expressRegion.loading = true;
  const resultData = await getRegionList(
    pageData.expressRegion.pagination.current,
    pageData.expressRegion.pagination.pageSize,
    pageData.expressRegion.filterValue
  );

  if (resultData.code === 200) {
    pageData.expressRegion.data = resultData.data;
    pageData.expressRegion.loading = false;
    pageData.expressRegion.pagination.total = resultData.data.total;
    pageData.expressRegion.pagination.current = resultData.data.current;
    pageData.expressRegion.pagination.pageSize = resultData.data.size;
  }
};

const handleExpressRegionConfirm = (e: Record<string, any>) => {
  pageData.formData.products[pageData.expressRegion.rowIndex].expressCountry = e.options.currentRowData.id;
  pageData.formData.products[pageData.expressRegion.rowIndex].expressCountryName = e.options.currentRowData.countryName;
  pageData.expressRegion.show = false;
};

const handleExpressRegionClose = () => {
  pageData.expressRegion.show = false;
};

const handleExpressRegionFilterChange = (filters: Record<string, any>) => {
  pageData.expressRegion.filterValue = filters;
  pageData.expressRegion.pagination = structuredClone(PAGINATION_VALUE);
  getExpressRegionData();
};

const handleExpressRegionPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.expressRegion.pagination.pageSize = pageInfo.pageSize;
  pageData.expressRegion.pagination.current = pageInfo.current;
  getExpressRegionData();
};

watch(
  () => pageData.formData.products,
  (newVal: Record<string, any>) => {
    if (Array.isArray(newVal) && newVal.length > 0) {
      const kgsTotalNum = newVal.reduce((acc: number, cur: Record<string, any>) => {
        return acc + Number(cur.kgs);
      }, 0);

      const gwsTotalNum = newVal.reduce((acc: number, cur: Record<string, any>) => {
        return acc + Number(cur.gws);
      }, 0);

      const bulkTotalNum = newVal.reduce((acc: number, cur: Record<string, any>) => {
        return acc + Number(cur.bulk);
      }, 0);

      pageData.formData.kgsTotalNum = newPrecision(kgsTotalNum, 3);
      pageData.formData.gwsTotalNum = newPrecision(gwsTotalNum, 3);
      pageData.formData.bulkTotalNum = newPrecision(bulkTotalNum, 1);
    }
  },
  { deep: true, flush: "post" }
);

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();

  /* validateResult 在校验没通过的时候返回的是一个 Object，校验通过的时候返回的是
   * 布尔值 true，所以这里写死判断为 true。
   */
  if (validateResult !== true) {
    return;
  }

  let resultData;

  if (props.mode === "view") {
    handleClose();
    return;
  }

  // console.log(toRaw(pageData.formData));
  const postFormData = toRaw(pageData.formData);

  // 排除尚未保存但已被标记删除的数据
  postFormData.products = postFormData.products.filter(
    (item: Record<string, any>) => !(item.id === "" && item.hasDeleted === 1)
  );

  if (props.mode === "new") {
    // 新增
    resultData = await http("POST", CREATE_FORM_PATH, postFormData);
  } else {
    resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
  }

  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (resultData.code === 200) {
    emits("close", "success");
  }
};

const handleClose = () => {
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
getRegulatorsDict();
getExpressMethodDict();
getFreeTaxNatureDict();
</script>
